<?php
$this->useClass("Action_Community_FeedHandler");
class Action_Node_ShowFeed extends Action_Community_FeedHandler
{
	public function getFeedModel() {
		$this->rh->UseClass("AggregatedModel_Feed_FeedInterface");
		$this->rh->UseClass("AggregatedModel_Feed_ReaderItems");

		return new AggregatedModel_Feed_ReaderItems();
	}

	var $ajax_functions = array(
		'ajax_getSomePosts'
		);

	public function ajax_getSomePosts( $page_number ) {

		$this->setParam("page_number", $page_number);

		$this->model->doStuff();

		$view = $this->rh->views->findByName('feed_items');
		$view->data = $this->acl_assistant->template_data;
		$items = $this->model->getItems();
		$view->data['items'] = $items;
		$items_node = $this->rh->ctx->cp->add_node("items");
		$items_node->set_data( $view->getContent() ); // рендеринг итемов

		$this->addPagerNodes ($this->rh->ctx->cp);
	}

	protected function init() {
		parent::init();
		$this->rh->UseClass("RL_URLGenerator");
	}

	public function getWidgetsConfig ()
	{
		$widgets = array(
			'0' => array (
				'name' => 'NodeTagsWidget',
				'params' => array(
					//'community_oid' => $this->aa->acl_data['comity_oid'],
					//'tdi_oid'=> $this->aa->acl_data['tdi_oid'],
					'tag' => $this->getParam('tag'),
					'from' => 'node',
					'widget_position' => 'tags',
					//'widget_view' => 'WG_TagsWidget',
				),
			),
		);

		return $widgets;
	} // end of function getWidgetsConfig

	private function processItems($items) {
		foreach ($items as $i=>$item) {

			$items[ $i ]['section'] = $this->sections[ $item['post']['tdi_oid'] ];
			$items[ $i ]['acl'] = $this->aa->getAcl( $item['post']['oid'] );

			if ($item['post']['type'] == 'fvote') {
				$ug = new RL_URLGenerator($this->rh->router->getRule("vote_manager")); //
				$ug->setRouter($this->rh->router);
				$ug->setParams(array(
					"community_url"=>$this->params['community_url'],
					"id_item"=>$item['post']['oid'],
					)
				);
				$items[ $i ]['vote_url'] = $ug->generateUrl();
				unset($ug);

				if ($item['post']['posted_by_id'] == $this->aa->acl_data['user_id']) {
					if ( $item['vote_closed'] ) {
						$items[$i]['can_open'] = 1;
					} else {
						$items[$i]['can_close'] = 1;
					}
				}
			}
		}

		return $items;
	}

	public function determineCustomModelParams() {
		$this->setParam("join_community", 1);
	}


	public function process ()
	{
		$aa = &$this->aa;
		//if (!$aa->is_granted(array('item_read'))) {
		//	echo "access denied";
		//	return false;
		//}

		$aa->checkDeletions( array($this, "shutdown") );

		$this->model->doStuff();

		$view = $this->rh->views->findByName('feed_site');
		$view->data = $aa->template_data;

		$view->data['can_create'] = $aa->is_granted(array('item_create', 'item_create_premod'));

		$items = $this->model->getItems();

		/**
		 * если какой юзер правил топик, надо подтянуть его данные
		 */
		foreach ( $items as $key=>$val ) {
			if ( isset($val['post']['edited_user_oid']) && !empty($val['post']['edited_user_oid']) ) {
				$object = $this->ctx->store->getObject($val['post']['edited_user_oid']);
				$items[$key]['post']['edited_user'] = $object->data;
			}
		}

		if ($items) {
			$view->data['items'] = $this->processItems($items);

		} else {
			$view->data['message'] = "В этой ленте нет сообщений.";
		}

		// данные для постраничной листалки
		$pager = $this->getPagerInfo();
		$view->data['page'] = $pager;
		$view->data['items_remaining'] = $pager['items_remaining'];


		$tag = $this->getParam('tag'); // instanceof fobject

		if ($tag) {
			$view->data['current_tag'] = $tag->data;
			$view->data['tag'] = $tag;
		}
		$view->data['tag_sections']['single'] = count($tdis) == 1 || isset($this->params['tdi_url']);
		// --- sections --- }}}

		$view->data['__widgets__'] = $this->widgets;

		// генерация урл адресов
		$this->rh->UseClass("RL_URLGenerator");
		$ug = new RL_URLGenerator($this->rh->router->getLastMatched()); //$this->rh->router->getRule('object_undelete')
		$ug->setRouter($this->rh->router);
		$ug->setParams($this->params);

		// урл для постраничной листалки без ajax
		if (isset($pager['prev'])) {
			$ug->setGet(array_merge($this->rh->GET, array("p"=>$pager['prev'])));
			$view->data["prev_url"] = $ug->generateUrl();
		}

		if (isset($pager['next'])) {
			$ug->setGet(array_merge($this->rh->GET, array("p"=>$pager['next'])));
			$view->data["next_url"] = $ug->generateUrl();
		}

		unset($ug);

		// для постраничной листалки ajax handler
		$ug = new RL_URLGenerator($this->rh->router->getRule('site_showfeed'));
		$ug->setRouter($this->rh->router);
		$ug->setParams($this->params);
		$ug->setGet($this->rh->GET);

		$view->data['ajax_url'] = $ug->generateUrl();

		// решим, выводить ли нам кнопку "Создать запись"
		if ( isset($this->params['tdi_url']) ) {
			// мы в разделе - проверяем можно ли в него писать
			$view->data['show_item_create_button'] = $aa->is_granted(array('item_create', 'item_create_premod'));
		} else {
			// мы в общей ленте - вывести кнопку если хоть в один раздел можно писать
			$show_button = false;
			if ($show_button) $view->data['show_item_create_button'] = 1;
		}

		$view->data['is_showfeed'] = true;

		$this->rh->response->setContent( $view );
	} // end of function execute

}
